package com.cheetah.start.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgentInfo;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;

import javax.servlet.http.HttpServletRequest;

/**
 * @author x
 * @date 2021/08/02
 */
public class MyIpUtil {

    /**
     * 获得 ip 地址
     *
     * @param request 请求
     * @return {@link String}
     */
    public static String getIpAddress(HttpServletRequest request) {
        if (request == null) {
            return UserAgentInfo.NameUnknown;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UserAgentInfo.NameUnknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UserAgentInfo.NameUnknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || UserAgentInfo.NameUnknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UserAgentInfo.NameUnknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || UserAgentInfo.NameUnknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * ip 移除端口
     *
     * @param request 请求
     * @return {@link String}
     */
    public static String getIpNotHavePort(HttpServletRequest request) {
        String ipAddress = getIpAddress(request);
        return removePort(ipAddress);
    }

    /**
     * 移除端口号
     *
     * @param ip ip
     * @return {@link String}
     */
    public static String removePort(String ip) {
        if (ip.contains(StrUtil.COLON)) {
            int i = ip.lastIndexOf(StrUtil.COLON);
            return ip.substring(0, i);
        }
        return ip;
    }

    /**
     * 获得ip地址和地区
     *
     * @param request        请求
     * @param regionSearcher 地区搜索器
     * @return {@link String}
     */
    public static String getIpWithAddress(HttpServletRequest request, Ip2regionSearcher regionSearcher) {
        String ipNotHavePort = getIpNotHavePort(request);
        String address = regionSearcher.getAddress(ipNotHavePort);
        return ipNotHavePort + "|" + address;
    }
}
